package com.lym.order;

import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

@EnableFeignClients // 开启Feign远程调用功能
@EnableDiscoveryClient //开启服务发现功能
@SpringBootApplication
public class OrderMainApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrderMainApplication.class, args);
    }

    /**
     * 需求: Nacos配置文件一旦发生信息变化,就通过邮件告知.
     * 核心: 通过监听器NacosConfigManager监听配置文件变化
     * 1、项目启动就监听配置文件变化
     * 2、发生变化后拿到变化值
     * 3、通过邮件发送通知
     */
    @Bean
    ApplicationRunner applicationRunner (NacosConfigManager nacosConfigManager) {
        return new ApplicationRunner() {
            @Override
            public void run(ApplicationArguments args) throws Exception {
                ConfigService configService = nacosConfigManager.getConfigService();
                // 添加监听器
                configService.addListener("service-order.properties", "DEFAULT_GROUP", new Listener() {
                    /**
                     * 监听器线程池
                     * @return
                     */
                    @Override
                    public Executor getExecutor() {
                        return Executors.newFixedThreadPool(4);
                    }

                    /**
                     * 接收配置信息
                     * @param reciveInfo
                     */
                    @Override
                    public void receiveConfigInfo(String reciveInfo) {
                        System.out.println(
                                "=================================\n" +
                                "监听到配置文件变化, 变化值: \n" +
                                reciveInfo +
                                "\n================================="
                        );
                        System.out.println("发送邮件通知 ... ...");
                    }
                });

                System.out.println("监听器启动成功 ... ...");
            }
        };
    }

}
